<template>
  <div>
    <main-nav index="1"></main-nav>
    <div class="container margin-top-15 detail-header clearfix">
      <h1>
        <span>{{item && item.title}}</span>
      </h1>
      <p v-if="item && item.id">
        <span>{{item.viewed}} 次浏览</span>
        <i>|</i>
        <span>{{item.recommended}} 次推荐</span>
        <i>|</i>
        <span>{{totalComments}} 条评论</span>
        <i v-if="!isNews">|</i>
        <grade-span :index="item.grade" v-if="!isNews"></grade-span>
        <subject-span :index="item.subject" v-if="!isNews"></subject-span>
        <a
          v-if="!isNews"
          target="_blank"
          class="pull-right"
          :href="'/vts/download/redirect/' + currentFile.id + '?token=' + getTicket()"
          v-show="item && item.attachmentsEnableDownload && currentFile"
        >下载课件</a>
      </p>
    </div>
    <div class="container margin-top-10 player-container" v-if="item && item.id">
      <div v-if="currentFile && currentFile.initialized">
        <div v-if="currentFile.isVideo">
          <video-player
            class="video-player-box"
            ref="videoPlayer"
            :options="playerOptions"
            :playsinline="true"
            @ready="playerReady"
          ></video-player>
        </div>
        <div class="inner" v-else>
          <img :src="picture" v-for="(picture, index) in pictures" :key="'pic_' + index">
        </div>
      </div>
      <ul class="nav-helper">
        <li>
          <a
            href="javascript:;"
            :class="{'active': item.wasRecommended}"
            @click="toggleRecommended()"
          >
            <i-icon type="thumbsup"></i-icon>
            <span class="text">推荐</span>
          </a>
        </li>
        <li>
          <a
            href="javascript:;"
            :class="{'active': item.wasFavored}"
            @click="toggleFavored()"
            v-if="!isNews"
          >
            <i-icon type="heart"></i-icon>
            <span class="text">收藏</span>
          </a>
        </li>
        <li>
          <a href="javascript:;" @click="scrollToComment()">
            <i-icon type="chatbox-working"></i-icon>
            <span class="text">评论</span>
          </a>
        </li>
        <li>
          <a href="javascript:;" @click="newNote()" v-if="!isNews">
            <i-icon type="document-text"></i-icon>
            <span class="text">记笔记</span>
          </a>
        </li>
      </ul>
      <i-row class="margin-top-20" :gutter="20">
        <i-col :md="16">
          <i-tabs type="card" @on-click="tabChanged" id="tabs">
            <i-tab-pane label="评论">
              <comment-new :objectId="item.id"></comment-new>
              <comment-list :objectId="item.id" ref="comments"></comment-list>
            </i-tab-pane>
            <i-tab-pane label="问答" v-show="item" v-if="!isNews">
              <router-link
                :to="{name: 'new-question', query: {courseId: item.id}}"
                class="ivu-btn ivu-btn-primary margin-bottom-10"
              >
                <span>提问</span>
              </router-link>
              <post-item
                :data="question"
                v-for="(question, index) in posts"
                :key="'course_post_' + index"
              ></post-item>
              <i-page
                class-name="margin-top-10 pull-right"
                v-show="totalPosts"
                :page-size="20"
                :total="totalPosts"
                :current="pager.question"
                size="small"
                @on-change="search('questions')"
                show-total
                show-elevator
              ></i-page>
              <p v-if="!totalPosts">暂无数据</p>
            </i-tab-pane>
            <i-tab-pane label="笔记" v-if="!isNews">
              <note-item
                @edit="editNote(note)"
                @search="search('notes')"
                :data="note"
                v-for="(note, index) in notes"
                :key="'course_note_' + index"
              ></note-item>
              <i-page
                class-name="pull-right"
                class="margin-top-10"
                v-show="totalNotes"
                :page-size="20"
                :total="totalNotes"
                :current="pager.note"
                size="small"
                @on-change="search('notes')"
                show-total
                show-elevator
              ></i-page>
              <p v-if="!totalNotes">暂无数据</p>
            </i-tab-pane>
          </i-tabs>
        </i-col>
        <i-col :md="8" class="course-items">
          <i-card class="course-description" dis-hover v-if="!isNews">
            <p slot="title">课程简介</p>
            <img
              src="../../images/default-avatar.png"
              width="80"
              class="display-block"
              style="margin:0 auto;"
            >
            <p class="course-author">{{item.createdBy.name}}</p>
            <p class="question margin-top-10">问：本课程中涉及到的知识点有哪些？</p>
            <p class="answer">答：{{item.tags.join('，')}}</p>
            <p class="question">问：我能学到什么？</p>
            <p class="answer">答：{{item.description || '看完就知道了'}}</p>
          </i-card>
          <i-card class="course-description" dis-hover v-if="isNews">
            <p slot="title">新闻简介</p>
            <img
              src="../../images/default-avatar.png"
              width="80"
              class="display-block"
              style="margin:0 auto;"
            >
            <p class="course-author">{{item.createdBy.name}}</p>
            <p class="question margin-top-10">新闻关键字：</p>
            <p class="answer">{{item.tags.join('，')}}</p>
            <p class="question">内容描述：</p>
            <p class="answer">{{item.description || '看完就知道了'}}</p>
          </i-card>
          <i-card class="course-files margin-top-10" dis-hover>
            <p slot="title">目录</p>
            <ul>
              <li v-for="(file, index) in item.files" :key="'course_' + item.id + '_' + index">
                <router-link
                  :class="{active: index == currentFileIndex}"
                  :to="{name: 'course-detail', params: {id: item.id, index: index}}"
                  :title="file.name"
                >{{file.name}}</router-link>
              </li>
            </ul>
          </i-card>
          <i-card class="related-courses margin-top-10" v-if="relatedCourses.length" dis-hover>
            <p slot="title">相关推荐</p>
            <ul>
              <li v-for="course in relatedCourses" :key="'related_course_' + course.id">
                <router-link
                  :to="{name: 'course-detail', params: {id: course.id}}"
                  :title="course.name"
                >{{course.name}}</router-link>
              </li>
            </ul>
          </i-card>
        </i-col>
      </i-row>
    </div>
    <note-form ref="note-form"></note-form>
  </div>
</template>

<script>
import 'video.js/dist/video-js.css'
import MainNav from '../components/main-nav'
import GradeSpan from '../components/data-span/Grade'
import SubjectSpan from '../components/data-span/Subject'
import CommentNew from '../components/comment/New'
import CommentList from '../components/comment/List'
import PostItem from '../components/post-item'
import NoteItem from '../components/note-item'
import TagSelector from '../components/tag-selector'
import NoteForm from '../components/note-form'
import { videoPlayer } from 'vue-video-player'

import { mapActions, mapGetters } from 'vuex'
export default {
  data() {
    return {
      item: null,
      currentFileIndex: 0,
      relatedCourses: [],
      pictures: [],
      pager: {
        note: 1,
        question: 1
      }
    }
  },
  components: {
    MainNav,
    GradeSpan,
    SubjectSpan,
    videoPlayer,
    CommentNew,
    CommentList,
    PostItem,
    TagSelector,
    NoteItem,
    NoteForm
  },
  methods: {
    ...mapActions({
      getLesson: 'getLesson',
      getRelatedCourses: 'getRelatedCourses',
      addEvent: 'addEvent',
      searchPosts: 'searchPosts',
      searchNotes: 'searchNotes'
    }),
    scrollToComment() {
      document.getElementById('tabs').scrollIntoView()
    },
    newNote() {
      this.$refs['note-form'].new({
        courseId: this.item.id,
        title: this.item.title,
        tags: this.item.tags,
        subject: this.item.subject,
        grade: this.item.grade
      })
    },
    search(type) {
      switch (type) {
        case 'notes':
          this.searchNotes({
            page: this.pager.note,
            courseId: this.item.id
          })
          break
        case 'questions':
          this.searchPosts({
            page: this.pager.question,
            courseId: this.item.id
          })
          break
      }
    },
    getTicket() {
      return localStorage.ticket
    },
    playerReady(player) {
      const containerStyle = player.el_.style
      const style = player.tech_.el_.style
      containerStyle.maxHeight = style.maxHeight = '480px'
      containerStyle.minHeight = style.minHeight = '280px'
      containerStyle.height = style.height = 'auto'
      containerStyle.width = style.width = '100%'
      style.position = 'relative'
    },
    tabChanged(index) {
      switch (index) {
        case 1:
          this.pager.question = 1
          this.search('questions')
          break
        case 2:
          this.pager.note = 1
          this.search('notes')
          break
        default:
          break
      }
    },
    toggleRecommended() {
      if (this.item && this.item.id) {
        const that = this
        this.addEvent({
          model: {
            id: this.item.id,
            type: 'RecommendCourse'
          },
          callback(result) {
            that.item.wasRecommended = result > 0
            that.$Message.success(
              that.item.wasRecommended ? '推荐成功' : '取消推荐成功'
            )
          }
        })
      }
    },
    toggleFavored() {
      if (this.item && this.item.id) {
        const that = this
        this.addEvent({
          model: {
            id: this.item.id,
            type: 'FavorCourse'
          },
          callback(result) {
            that.item.wasFavored = result > 0
            that.$Message.success(
              that.item.wasFavored ? '已加入收藏夹' : '已从收藏中移除'
            )
          }
        })
      }
    },
    editNote(item) {
      this.$refs['note-form'].new({
        id: item.id,
        courseId: item.courseId,
        title: item.title,
        tags: item.tags,
        description: item.description,
        subject: this.item.subject,
        grade: this.item.grade
      })
    },
    initFile(file) {
      if (file.initialized === true) return
      file.isVideo = file.type.indexOf('video') !== -1
      const that = this
      if (!file.isVideo) {
        file.pictures = []
        that.$http.get('/vts/document/get/' + file.id).then(response => {
          that.pictures = file.pictures = response.data
        })
      }
      file.initialized = true
    }
  },
  computed: {
    ...mapGetters({
      totalPosts: 'totalPosts',
      totalNotes: 'totalNotes',
      posts: 'posts',
      notes: 'notes',
      totalComments: 'totalComments'
    }),
    isNews() {
      return this.item && this.item.courseType === 1
    },
    currentFile() {
      const that = this
      if (!that.item || !that.item.files) return
      var file = that.item.files[that.currentFileIndex]
      that.initFile(file)
      return file
    },
    playerOptions() {
      var file = this.currentFile
      var path = file.path.replace('.html5', '.mp4')
      if (path.endsWith('.flv')) path += '.mp4'

      return {
        // videojs options
        playbackRates: [0.7, 1.0, 1.5, 2.0],
        sources: [
          {
            type: 'video/mp4',
            src: path
          }
        ],
        poster: file.avatar
      }
    }
  },

  mounted() {
    const that = this
    var id = this.$route.params.id
    if (id) {
      that.getLesson({
        id: id,
        callback(data) {
          that.item = data
        }
      })
      that.getRelatedCourses({
        id: id,
        callback(relatedCourses) {
          that.relatedCourses = relatedCourses
        }
      })
      that.addEvent({
        model: {
          id: id,
          type: 'BrowseCourse'
        },
        callback(result) {
          that.item && that.item.viewed++
        }
      })
      var index = this.$route.params.index
      this.currentFileIndex = index || 0
    } else {
      this.$router.push({ name: 'courses' })
    }
  }
}
</script>

<style lang="less" scoped>
.detail-header {
  h1 {
    font-weight: normal;
    font-size: 22px;
  }
  i {
    margin: 0 5px;
    color: gray;
  }
}
.player-container {
  position: relative;
  .inner {
    background: white;
    text-align: center;
    img {
      max-width: 100%;
    }
  }
  .nav-helper {
    position: absolute;
    top: 80px;
    @media (max-width: 767px) {
      top: 20px;
    }
    right: 15px;
    li + li {
      margin-top: 5px;
    }
    a {
      display: block;
      padding: 8px 0;
      width: 50px;
      text-align: center;
      background: #333;
      color: white;
      &:hover {
        background: #39f;
      }
      i {
        font-size: 16px;
      }
      span {
        display: block;
      }
    }
  }
}
h3 {
  font-size: 16px;
  padding: 10px 0;
  margin-top: 5px;
}
.course-files {
  margin-top: 20px;
  li {
    margin-bottom: 10px;
    a {
      padding: 10px 15px;
      display: block;
      color: #333;
      background: lighten(#999, 20%);
      font-size: 14px;
      word-break: keep-all;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      &.active,
      &:hover {
        color: white;
        background: #666;
      }
    }
  }
}
.course-items {
  .related-courses {
    margin-bottom: 30px;
    li {
      margin-bottom: 5px;
      a {
        color: #333;
        font-size: 14px;
        &:hover {
          color: #39f;
        }
      }
    }
  }
}
.course-description {
  .question {
    font-size: 14px;
    color: #000;
    margin-top: 10px;
  }
  .answer {
    font-size: 14px;
    color: #666;
    margin-top: 5px;
  }
  .course-author {
    text-align: center;
    font-size: 16px;
    font-weight: bold;
    margin-top: 5px;
    margin-bottom: 20px;
  }
}
</style>
